const cuttent = require('../models/CityLists')
const R = require('../utils/R')
class CityListsCtl {
    async find(ctx) {
        // 每页条数
        const perPage = parseInt(ctx.query.perPage) || 10
        // 当前页
        const page = parseInt(ctx.query.page) || 1
        // 跳过条数
        const skip = (page - 1) * perPage
        // 分页 模糊搜索
        const q = new RegExp(ctx.query.q)
        // 倒序
        const data = await cuttent.find({ name: q }).limit(perPage).skip(skip).sort({ createdAt: -1 })
        // 总条数
        const total = await cuttent.find({ name: q }).countDocuments()
        // 向上取整 一共有多少页
        const totalPage = Math.ceil(total / perPage)
        ctx.body = R.ok().data({
            data,
            page,
            perPage,
            total,
            totalPage,
        })
    }
    async create(ctx) {
        ctx.verifyParams({
            name: { type: 'string', required: true }
        })
        const { name } = ctx.request.body
        let data = null
        data = await cuttent.findOne({ name })
        if (data) {
            ctx.body = R.setResult({ status: 10000, message: '数据重复'}).data(null)
            return
        }
        data = await new cuttent(ctx.request.body).save()
        ctx.body = R.ok().data(data)
    }

    async update(ctx) {
        ctx.verifyParams({
            name: { type: 'string', required: true },
        })
        var data = await cuttent.findByIdAndUpdate(ctx.params.id, ctx.request.body, {
            new: true
        })
        if (!data) {
            ctx.body = R.setResult({ status: 10001, message: '数据不存在'}).data(null)
            return
        }
        ctx.body = R.ok().data(data)
    }
}


module.exports = new CityListsCtl()